package 八数码;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
    static int[] dx = {1, -1, 0, 0};
    static int[] dy = {0, 0, -1, 1};

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String start = "";
        for (int i = 0; i < 9; i++) {
            String ch = in.next();
            start += ch;
        }
        System.out.println(bfs(start));
    }

    private static int bfs(String start) {
        String end = "12345678x";
        Queue<String> q = new LinkedList<>();
        HashMap<String, Integer> map = new HashMap<>();
        q.offer(start);
        map.put(start, 0);
        while (!q.isEmpty()) {
            String t = q.poll();
            if (t.equals(end)) {
                return map.get(t);
            }
            int k = t.indexOf('x');
            int x = k / 3;
            int y = k % 3;
            for (int i = 0; i < 4; i++) {
                int a = x + dx[i];
                int b = y + dy[i];
                if (a < 0 || a >= 3 || b < 0 || b >= 3) {
                    continue;
                }
                char[] tmp = t.toCharArray();
                swap(tmp, k, 3 * a + b);
                String s = new String(tmp);
                if (map.get(s) == null) {
                    q.offer(s);
                    map.put(s, map.get(t) + 1);
                }
            }
        }
        return -1;
    }

    private static void swap(char[] tmp, int x, int y) {
        char t = tmp[x];
        tmp[x] = tmp[y];
        tmp[y] = t;
    }

}
